import React from 'react';
import InputItem from '../../../components/InputItem';
import DepartmentController from '@/services/System/DepartmentController';
import {Input,InputNumber, message, Select,Upload,Button,Table,Modal,Popover} from 'antd';
import { UploadOutlined,PlusOutlined } from '@ant-design/icons';
import { CURRENT_ENV,hostMap } from '@/ajax/config';
import OfferedController from '@/services/OfferedProject/OfferedController';

const {TextArea}= Input
const {confirm} = Modal
class NewProjectOne extends React.Component {
    constructor(props) {
        super(props);
        this.state = { 
            datas:{},
            departmentList:[],
            userInfo:JSON.parse(sessionStorage.getItem('userInfo')),
            freshen:false,
            dataSource:[]
         };
        this.getDepartmentList()

    }
    componentDidMount(){
        this.props.onRef(this)
    }
    handleChange=(key,value)=>{
        let {datas} = this.state
        datas[key] = value.target?value.target.value :value
        this.setState({datas})
    }
    getDepartmentList=()=>{
        let {userInfo} = this.state
        let provinceDepartmentList = []
        let cityDepartmentList = []
        let departmentList = []
        DepartmentController.getList({to_stop:'1'}).then(r=>{
            if(r&&r.status===200){
                r.data.rows.map(item=>{
                    if(item.type==='省级'){
                        provinceDepartmentList.push({code:item.id,name:item.name})}
                    if(item.type==='市级'){
                        cityDepartmentList.push({code:item.id,name:item.name})}
                })
                if(userInfo.roleName.indexOf('市级')!==-1){
                    departmentList = cityDepartmentList
                }
                if(userInfo.roleName.indexOf('省级')!==-1){
                    departmentList = provinceDepartmentList
                }

                this.setState({departmentList})
            }
        })
    }
    fileChange=(info)=>{        
        let fileList = [...info.fileList];
        fileList = fileList.slice(-2);
        fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    this.setState({ fileList });
    }
    freshen=()=>{
        this.setState({freshen:!this.state.freshen})
    }
    textChange=(e)=>{
        this.setState({description:e.target.value})
    }
    deleteItem=(index)=>{
        let {dataSource} = this.state
        dataSource.splice(index,1)
        this.setState({dataSource})
        this.freshen()

    }
    addItem=()=>{
        let {dataSource,fileList,description} = this.state
        if(fileList.length===0){
            message.error('请上传文件')
            return
        }
        dataSource.push({url:fileList[0].response,description,fileName:fileList[0].name})
        console.log(dataSource)
        this.setState({dataSource,visible:false,fileList:[],description:''})
        this.freshen()
    }
    getStr=(str)=>{
        let result =''
        if(str.length>15){
            result=str.slice(0,15)+"……"
        }else{
            result=str
        }
        return result;
    }
    submit=()=>{
        let that = this
        let {userInfo,datas,dataSource} = this.state
        if(!datas.projectName){
            message.error('请输入项目名称')
            return;
        }
        if(!datas.description){
            message.error('请输入项目描述')
            return;
        }
        if(!datas.participantNumber){
            message.error('请输入领取人数')
            return;
        }
        if(!datas.department){
            message.error('请选择归属部门')
            return;
        }
        let projectLevel=''
        if(userInfo.roleName.indexOf("省级")!==-1){
            projectLevel='省级'
        }
        if(userInfo.roleName.indexOf("市级")!==-1){
        projectLevel='市级'
        }
       
        let params = {
            ...datas,
            level:projectLevel,
            fileItems:JSON.stringify(dataSource),
            userName: userInfo.userName,
        }
          confirm({
            title:'提示',
            content:'确定要提交吗？',
            onOk(){
              OfferedController.createdProject(params).then(r=>{
                if(r&&r.data===1){
                message.success('提交成功')
                }
                else{
                  message.error('提交失败，请稍后再试')
                }
                that.props.onCancel()
              })
             
            }
          })          
        
      }


    render() {
        const {datas,departmentList,freshen,visible,userInfo,dataSource} = this.state
        const columns=[
            {title:'序号',dataIndex:'url',render:(text,row,index)=>index+1},
            {title:'文件名',dataIndex:'fileName'},
            {title:'描述',dataIndex:'description',render:text=><Popover placement="topLeft" title={'详情'} content={text} trigger="click" >{text&&this.getStr(text)}</Popover>},
            {title:'操作',dataIndex:'',render:(text,row,index)=><a onClick={this.deleteItem.bind(this,index)}>删除</a>},
        ]
        return (
            <div>
                <div style={{margin:5}}>
                    <strong>任务名称：</strong>
                    <Input onChange={this.handleChange.bind(this,'projectName')} style={{width:400}} value={datas.projectName}></Input>
                </div>
                <div style={{margin:5}}>
                    <strong style={{verticalAlign:'top'}}>任务描述：</strong>
                    <Input.TextArea onChange={this.handleChange.bind(this,'description')} style={{width:400}} value={datas.description}></Input.TextArea>
                </div>
                <div style={{margin:5}}>
                    <strong>认领人数：</strong>
                    <InputNumber onChange={this.handleChange.bind(this,'participantNumber')} min={0} style={{width:400}} value={datas.participantNumber}></InputNumber>
                </div>
                <div style={{margin:5}}>
                    <strong>所属部门：</strong>
                    <Select onChange={this.handleChange.bind(this,'department')} style={{width:400}} value={datas.department}>
                        {departmentList.map(item=><Select.Option value={item.code+"/"+item.name} key={item.code}>{item.name}</Select.Option>)}
                    </Select>
                </div>
                <div>
                <Button icon={<PlusOutlined/>} onClick={()=>this.setState({visible:true})} type={'primary'}>添加文件</Button>
                {freshen&&<Table dataSource={dataSource} columns={columns} bordered rowKey={'url'} />}
                {!freshen&&<Table dataSource={dataSource} columns={columns} bordered rowKey={'url'} />}
                {visible&&<Modal
                visible={visible}
                title={'新增'}
                onCancel={()=>this.setState({visible:false})}
                onOk={this.addItem}
                >
                <Upload
                    action= {hostMap[CURRENT_ENV]+"/upload"}
                    onChange= {this.fileChange}
                    headers={{"token":userInfo.token}}
                    fileList={this.state.fileList}
                    >
                        <span><Button icon={<UploadOutlined />} style={{width:400}}>上传</Button></span>
                </Upload>
                <TextArea placeholder={'请输入'} onChange={this.textChange.bind(this)}/>
                </Modal>}
            </div>
            </div>
        );
    }
}

export default NewProjectOne;